<template>

  <a-modal
    title="新增客户资料"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="客户资料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入客户资料名称"
                v-decorator="['cusInforName', { rules: [{ required: true, message: '请输入客户资料名称！' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="社会统一信用代码" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入社会统一信用代码(18位)"
                allowClear
                :maxLength="18"
                v-decorator="['code', { rules: [{ required: true, validator: validatorCode }]}]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="客户分类" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-tree-select
                v-decorator="[
                  'cusSortId',
                  { initialValue: selCusSortId, rules: [{ required: true, message: '请选择客户分类！' }] },
                ]"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                :treeData="cusTree"
                placeholder="请选择客户分类"
              >
                <span slot="title" slot-scope="{ id }">{{ id }} </span>
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>

        <cus-person-table-form-item
          ref="cusPersonTable"
          :oldTableData="cusPersonList"
          @tableDataChange="(data) => {cusPersonList = data}"
          @add="({tableData})=>{ cusPersonList = tableData}"
          @del="({tableData})=>{ cusPersonList = tableData}"
        />

        <a-form-item label="备注信息" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
          <a-textarea
            :rows="3"
            placeholder="请输入备注信息"
            v-decorator="['remark']"
            :auto-size="{ minRows: 3, maxRows: 6 }"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { cusInforAdd } from '@/api/modular/main/cusinfor/cusInforManage'
import { getCusTree } from '@/api/modular/main/cussort/cusSortManage'
import cusPersonTableFormItem from '@/views/main/cusinfor/cusPersonTableFormItem'

export default {
  components: {
    cusPersonTableFormItem
  },
  props: {
    selCusSortId: {
      default: null,
      type: String,
      required: false
    },
    // eslint-disable-next-line vue/require-prop-types
    cusInforLists: {
      default: null
    }
  },
  data() {
    return {
      cusPersonList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol_T: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol_T: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      cusTree: [],
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      cusSortIdData: []
    }
  },
  methods: {
    // 初始化方法
    async add(record) {
      this.visible = true
      const dataList = await this.getCusTree()
      // 设置初始值
      setTimeout(() => {
        this.form.setFieldsValue({
          cusSortId: dataList.length !== 0 ? this.cusTree[0].id : ''
        })
      }, 100)
    },
    /**
     * 获取类型树，并加载于表单中
     */
    async getCusTree() {
      var promise = getCusTree().then((res) => {
        this.formLoading = false
        if (!res.success) {
          this.cusTree = []
          return
        }
        this.cusTree = res.data
      })
      await promise
      return this.cusTree
    },
    /**
     * 社会统一代码校验
     */
    validatorCode (rule, value) {
      const codeReg = /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/
      if (value === undefined) {
        return Promise.reject(new Error('请输入社会统一信用代码！'))
      } else {
        if (!codeReg.test(value)) {
          return Promise.reject(new Error('请输入社会统一信用代码共18位(第六位为数字,其他位为数字和大写字母组成)！'))
        }
        return Promise.resolve()
      }
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      // this.confirmLoading = false
      let isPhoneError = false
      let isPhoneEmpty = false
      let isNameEmpty = false
      let personName = ''
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            values[key] = (typeof values[key]) === 'string' ? values[key].trim() : values[key]
            if (typeof values[key] === 'object' && values[key] != null) {
              values[key] = JSON.stringify(values[key])
            }
          }
          const codes = this.cusInforLists
          for (var item of codes) {
            if (values.code === item.code) {
              this.$message.error('社会统一信用代码不能重复！')
              this.confirmLoading = false
               return
            }
          }
            values.cusPersonList = [...this.cusPersonList]
            // 联系人校验
            if (values.cusPersonList && values.cusPersonList !== []) {
              // 主联系人唯一校验
              var num = 0
              values.cusPersonList.forEach(item => {
                if (item.maiorCusPerson === '1') {
                  num++
                }
              })
              if (num >= 2) {
                this.$message.error('只能存在一个主联系人')
                this.confirmLoading = false
                return
              }
              values.cusPersonList.forEach(item => {
                const reg = /^1[3|4|5|7|8][0-9]{9}$/
                // 联系人为空
                if (item.cusPerson === '' || item.cusPerson === null) {
                  isNameEmpty = true
                }
                // 手机号码为空
                if (item.cusPhone === '' || item.cusPhone === null) {
                  isPhoneEmpty = true
                  personName = item.cusPerson
                  return
                }
                // 手机号码格式不正确
                if (!reg.test(item.cusPhone)) {
                  isPhoneError = true
                  personName = item.cusPerson
                  return false
                }
              })
              if (isNameEmpty) {
                this.$message.error('联系人为空')
                this.confirmLoading = false
                return
              }
              if (isPhoneEmpty) {
                this.$message.error('联系人 “' + personName + '” 的手机号码为空')
                this.confirmLoading = false
                return
              }
              if (isPhoneError) {
                this.$message.error('联系人 “' + personName + '” 的手机号码格式错误')
                this.confirmLoading = false
                return
              }
            }
            // 调用API
            cusInforAdd(values)
              .then((res) => {
                if (res.success) {
                  this.$message.success('新增成功')
                  this.confirmLoading = false
                  this.$emit('ok', values)
                  // 新增后更新联系人list
                  this.$emit('refreshCommonFormAllCusPersonList')
                  this.handleCancel()
                } else {
                  this.$message.error(res.message)// + res.message
                }
              }).finally((res) => {
                this.confirmLoading = false
              })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.cusPersonList = []
      this.$refs.cusPersonTable.clearTableData()
      this.visible = false
    }
  }
}
</script>
